# -*- coding: utf-8 -*-
import gettext
import locale
import os
from time import strftime, localtime


__SYSTEM_LOCALE_FOUND = False


# List all available languages.
Languages = [
    ('de_DE', 'Deutsch'),
    ('nl_NL', 'Nederlands'),
    ('es_ES', 'Español')
]


# Set searx-qt default language
Language = None


# Find system default
defaultLanguage, defaultEncoding = locale.getlocale()


# Set current language to system default if found.
index = 0
for key, name in Languages:
    if defaultLanguage == key:
        Language = Languages[index]
        break
    index += 1


def timeToString(time_):
    if __SYSTEM_LOCALE_FOUND:
        locale.setlocale(locale.LC_TIME, normalize(Language[0]))
    return strftime("%a %d %b %Y %H:%M:%S", localtime(time_))


def normalize(localeName):
    str_ = locale.normalize(localeName)
    enc = locale.getpreferredencoding(do_setlocale=True)
    str_ = str_.split('.', 1)[0]
    return str_ + "." + enc


def localeTest(normalizedLocaleName):
    try:
        locale.setlocale(locale.LC_TIME, normalizedLocaleName)
    except locale.Error:
        return False
    return True


_ = gettext.gettext
if Language:
    # Set LC_TIME if system locale found.
    __SYSTEM_LOCALE_FOUND = localeTest(
        normalize(Language[0])
    )

    if not __SYSTEM_LOCALE_FOUND:
        print("Warning! `{0}` not found. Cannot translate dates and time."
              .format(normalize(Language[0])))

    # Set local .mo file.
    lang = None
    try:
        # First try system locale directory
        lang = gettext.translation('searx-qt', languages=[Language[0]])
    except FileNotFoundError:

        xdgDataHome = os.getenv('XDG_DATA_HOME')
        if xdgDataHome is not None:

            localeDir = os.path.join(xdgDataHome, 'locale')

            try:
                lang = gettext.translation('searx-qt', localedir=localeDir,
                                           languages=[Language[0]])
            except FileNotFoundError:
                pass

    if lang:
        lang.install()
        _ = lang.gettext
    else:
        print("Warning! Locale file (.mo) for language `{0}` not found!"
              .format(Language[0]))
